<template>
  <el-dialog
    v-if="visible"
    v-model="visible"
    class="component-update-user-balance"
    :title="isBatchRecharge ? $t('user.balanceRecharge') : $t('user.balanceUpdate')"
    width="30%"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="isBatchRecharge ? batchDataRule : dataRule"
      :label-width="$t('language') === 'English' ? '130px' : '80px'"
      @submit.prevent
    >
      <el-form-item
        :label="$t('user.changeQuantity')"
        prop="balanceValue"
      >
        <el-input-number
          v-model="dataForm.balanceValue"
          type="number"
          :controls="false"
          class="balancev-value"
          :step="0.01"
          step-strictly
          @change="onInputNumber"
        />
        <br>
        <!-- 批量更改余额 - 批量给用户充值余额，只能批量给用户增加余额，请输入大于零的数 -->
        <span v-if="isBatchRecharge === 1">{{ $t("user.balanceTip4") }}
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('user.balanceTip8')"
            placement="top"
          >
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
        <!-- 修改指定会员余额 - 正数代表增加，负数代表减少，只能输入数字，最多两位小数 -->
        <span v-if="isBatchRecharge !== 1">{{ $t("user.balanceTip1") }}</span>
        <!-- 修改指定会员余额 - 用户当前余额为X -->
        <div v-if="isBatchRecharge !== 1">
          {{ $t("user.balanceTip6") + dataForm.balance }}
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('user.balanceTip7')"
            placement="top"
          >
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
      </el-form-item>

      <el-form-item>
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t("remindPop.cancel") }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onConfirm"
        >
          {{ $t("remindPop.confirm") }}
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import Big from 'big.js'
import { ElMessage } from 'element-plus'
const validate = (rule, value, callback) => {
  const flag = dataForm.balanceValue === 0 || dataForm.balanceValue === '0.0' || dataForm.balanceValue === '0.00'
  if (!/^(-)?[1-9]\d*$|^(-)?[1-9]\d*\.\d\d?$|^(-)?0\.\d\d?$/.test(value) || flag) {
    callback(new Error($t('user.balanceTip3')))
  } else {
    callback()
  }
}
const validateNumber = (rule, value, callback) => {
  const flag = dataForm.balanceValue === 0 || dataForm.balanceValue === '0.0' || dataForm.balanceValue === '0.00'
  if (!/^[1-9]\d*$|^[1-9]\d*\.\d\d?$|^0\.\d\d?$/.test(value) || flag) {
    callback(new Error($t('user.balanceTip5')))
  } else {
    callback()
  }
}
const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const confirmLoad = ref(false)
// 如果是批量充值，就展示批量充值部分内容 1是 0否
const isBatchRecharge = ref(0)
const dataForm = reactive({
  balanceValue: null,
  userIds: [],
  remark: null
})
const dataRule = {
  balanceValue: [
    { required: true, message: $t('user.balanceTip2'), trigger: 'blur' },
    { validator: validate, trigger: 'blur' }
  ]
}
const batchDataRule = {
  balanceValue: [
    { required: true, message: $t('user.balanceTip5'), trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ]
}

const init = (ids, type, balance) => {
  visible.value = true
  dataForm.userIds = ids
  dataForm.balanceValue = null
  if (!balance || balance < 0) {
    balance = 0
  }
  dataForm.balance = balance
  isBatchRecharge.value = type === 1 ? 1 : 0
}
const onInputNumber = () => {
  const maxBalance = new Big(999999999.99).minus(dataForm.balance)
  if (dataForm.balanceValue) {
    dataForm.balanceValue = Number(dataForm.balanceValue)
    // console.log(JSON.stringify(dataForm.balanceValue))
  }
  const balanceValue = parseFloat(dataForm.balanceValue)
  if (balanceValue > maxBalance) {
    dataForm.balanceValue = maxBalance
  } else if (balanceValue <= -dataForm.balance) {
    dataForm.balanceValue = -dataForm.balance
  }
}

const dataFormRef = ref(null)
const onConfirm = Debounce(function () {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }
    if (!dataForm.userIds) {
      return
    }
    confirmLoad.value = true
    const param = dataForm
    http({
      url: http.adornUrl('/user/userBalance/updateUserBalance'),
      method: 'put',
      data: http.adornData(param)
    }).then(({ data }) => {
      ElMessage({
        message: $t('remindPop.success'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          visible.value = false
          confirmLoad.value = false
          emit('refreshDataList', data.page)
          dataForm.balanceValue = null
        }
      })
    }).catch(() => {
      confirmLoad.value = false
    })
  })
}, 1000)
defineExpose({ init })
</script>
<style lang="scss" scoped>
.component-update-user-balance .balancev-value {
  width: 100%;
  display: block;
  :deep(.el-input input){
    text-align: left;
  }
}
</style>
